import Vue from 'vue';
import axios from 'axios';
Vue.prototype.$ajax = axios;
// 创建axios实例
axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
    // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  }
});

/*axios.all(
  '*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
  });*/

// request拦截器
axios.interceptors.request.use(config => {
  // config.headers['Authorization'] = Vue.cookie.get('token');
  if(Vue.cookie.get('token')){
    config.headers['Authorization'] = Vue.cookie.get('token');
  }else{
    
  }

  return config;
}, error => {
  return Promise.reject(error);
});

// response拦截器
axios.interceptors.response.use(response => {
  if (response.data && response.data.code === -1 ||
    response.data && response.data.code === 401) { // -1, token失效 401 没有token
    Vue.cookie.delete('token');
    Vue.router.push({name: '/'});
  }
  return response;
}, error => {
  return Promise.reject(error);
});

